package com.kwshare.user.controller;

import com.kwshare.common.core.domain.Response;
import com.kwshare.common.core.domain.system.OptionsSelect;
import com.kwshare.common.core.domain.user.Role;
import com.kwshare.common.core.utils.SecurityUtils;
import com.kwshare.user.service.IRoleService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色管理
 *
 * @author yangjing
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    private IRoleService roleService;

    /**
     * 获取角色列表信息
     *
     * @return 角色列表
     */
    @GetMapping("/list")
    public Response<?> list(String roleName){
        return Response.ok(roleService.getRoleList(roleName));
    }

    /**
     * 添加角色
     *
     * @param roleName 角色名称
     * @return 结果
     */
    @PostMapping
    public Response<?> add(HttpServletRequest httpServletRequest, String roleName){
        String username = SecurityUtils.getUsername(httpServletRequest);
        int insertRole = roleService.insertRole(roleName, username);
        if(insertRole == 1){
            return Response.ok();
        }else{
            return Response.fail();
        }
    }

    /**
     * 删除角色
     *
     * @param id 角色id
     * @return 结果
     */
    @DeleteMapping("/{id}")
    public Response<?> remove(@PathVariable Long id){
        int deleteRoleById = roleService.deleteRoleById(id);
        if(deleteRoleById == 1){
            return Response.ok();
        }else{
            return Response.fail("删除失败");
        }
    }

    /**
     * 更新角色
     *
     * @param role 角色
     * @return 结果
     */
    @PutMapping
    public Response<?> edit(@RequestBody Role role,HttpServletRequest httpServletRequest ){
        int updateRole = roleService.updateRole(role.getId(), role.getRoleName(), SecurityUtils.getUsername(httpServletRequest));
        if(updateRole == 1){
            return Response.ok();
        }else{
            return Response.fail("更新失败");
        }
    }

    /**
     * 获取角色选择框列表
     *
     * @return 结果
     */
    @GetMapping("/optionSelect")
    public Response<?> optionSelect(){
        List<Role> roles = roleService.getRoleAll();
        ArrayList<OptionsSelect> list = new ArrayList<>();
        for(Role role : roles){
            OptionsSelect optionsSelect = new OptionsSelect();
            optionsSelect.setValue(role.getId());
            optionsSelect.setLabel(role.getRoleName());
            list.add(optionsSelect);
        }
        return Response.ok(list);
    }
}
